package la.renzhen.rtpt.config.source.template;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 23/05/2018 10:54 AM
 */
@Slf4j
public class DiscoveryRestTemplateSelector extends SingleRestTemplateSelector {

    String serviceId;
    DiscoveryClient client;

    public DiscoveryRestTemplateSelector(String serviceId, DiscoveryClient client) {
        super();
        this.serviceId = serviceId;
        this.client = client;

    }

    private ServiceInstance getRTPTConfigServerInstance() {
        log.info("Locating rtpt config server ({}) via discovery", serviceId);
        List<ServiceInstance> instances = this.client.getInstances(serviceId);
        if (instances.isEmpty()) {
            throw new IllegalStateException("No instances found of rptp config server (" + serviceId + ")");
        }
        Optional<ServiceInstance> instance = instances.stream().findAny();
        if (!instance.isPresent()) {
            return null;
        }
        log.info("Locating rptp config server ( {} ) via discovery: {}", serviceId, instance.get().getUri());
        return instance.get();
    }


    @Override
    public String select(RestTemplate template) {
        ServiceInstance instance = getRTPTConfigServerInstance();
        return instance.getUri().toString();
    }
}
